package com.example.famhealing.report;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsoluteLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.famhealing.R;

public class ReportActivity extends Activity implements OnClickListener{

	// essence chart variable
	//private Chart sideEffect = null;
	
	private ImageButton week = null;
	private ImageButton month = null;
	
	int nRows = 20;
	int nColumns = 2;
	boolean isMonth = true;
	String urlStr="http://192.168.0.61:8080/famhealing/getReport.get?isMonth=1&phone_num=01011111111";

	ArrayList<Double> conditionValue=new ArrayList<Double>();
	double[][] sideEffectValue=new double[19][2];
	double conditionAvg=0;
	ArrayList<Double> weightValue=new ArrayList<Double>();
	double weightAvg=0;
	double weightHigh=0;
	double weightLow=9999;
	ArrayList<Double> temperValue=new ArrayList<Double>();
	double temperAvg=0;
	double temperHigh=0;
	double temperLow=9999;
	ArrayList<Double> heartRateValue=new ArrayList<Double>();
	double heartAvg=0;
	double heartHigh=0;
	double heartLow=9999;
	ArrayList<Double> pressureValue=new ArrayList<Double>();
	double pressureAvg=0;
	double pressureHigh=0;
	double pressureLow=9999;
	int[][] statusValue=new int[12][2];
	String[] statusStr=new String[5];
	
	//GridData gridData = null;
	ScrollView scroll=null;
	ImageButton top=null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_report);
		
		week = (ImageButton) findViewById(R.id.week_graph);
		month = (ImageButton) findViewById(R.id.month_graph);
		week.setOnClickListener(this);
		month.setOnClickListener(this);
		
		top=(ImageButton)findViewById(R.id.top);
		top.setOnClickListener(this);

		setReport();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.week_graph:
			if(isMonth==false)
				return;
			urlStr="http://192.168.0.61:8080/famhealing/getReport.get?isMonth=0&phone_num=01011111111";

			isMonth = false;
			break;
		case R.id.month_graph:
			if(isMonth==true)
				return;
			urlStr="http://192.168.0.61:8080/famhealing/getReport.get?isMonth=1&phone_num=01011111111";
			isMonth = true;
			break;
		case R.id.top:
			scroll=(ScrollView)findViewById(R.id.scrollView1);
			scroll.scrollTo(0, 0);
			break;
		}
		setReport();
	}
	
	void getData()
	{        
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());

		initData();
		try
		{
			URL url1=new URL(urlStr);
			InputStream in=url1.openStream();
			XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
			XmlPullParser parser=factory.newPullParser();
			
			parser.setInput(in, "euc-kr");
			
			int eventType=parser.getEventType();
			boolean isItemTag=false;
			boolean isDiary=false;
			String tagName="";
			String tmp="";
			
			while(eventType!=XmlPullParser.END_DOCUMENT)
			{
				if(eventType==XmlPullParser.START_TAG)
				{
					tagName=parser.getName();
					if(!tagName.equals("diary") && isDiary==false)
					{
						eventType=parser.next();
						continue;
					}
					if(tagName.equals("diary"))
					{
						isDiary=true;
						eventType=parser.next();
						continue;
					}
					if(!tagName.equals("diary") && isDiary==true)
						isItemTag=true;
				}
				else if(eventType==XmlPullParser.TEXT && isItemTag==true)
				{
					if(tagName.equals("cond"))
					{
						conditionValue.add(Double.parseDouble(parser.getText()));
					}
					else if(tagName.equals("side_effects"))
					{
						tmp=parser.getText();
						for(int i=0;i<19;i++)
						{
							if(tmp.split("/")[i].equals("1"))
							{
								sideEffectValue[i][0]++;
							}
						}
					}
					else if(tagName.equals("weight"))
					{
						weightValue.add(Double.parseDouble(parser.getText()));
					}
					else if(tagName.equals("temper"))
					{
						temperValue.add(Double.parseDouble(parser.getText()));
					}
					else if(tagName.equals("heart_rate"))
					{
						heartRateValue.add(Double.parseDouble(parser.getText()));
					}
					else if(tagName.equals("pressure"))
					{
						pressureValue.add(Double.parseDouble(parser.getText()));
					}
					else if(tagName.equals("status"))
					{
						tmp=parser.getText();
						
						for(int i=0;i<6;i++)
						{
							if(!tmp.split("/")[i].equals("0"))
							{
								statusValue[Integer.parseInt(tmp.split("/")[i])-1][0]++;
								statusValue[Integer.parseInt(tmp.split("/")[i])-1][1]=Integer.parseInt(parser.getText());
							}
						}
					}
				}
				else if(eventType==XmlPullParser.END_TAG)
					isItemTag=false;
				
				eventType=parser.next();
			}
			
			if(!conditionValue.isEmpty())
			{
				for(int i=0;i<conditionValue.size();i++)
				{
					conditionAvg+=conditionValue.get(i);
				}
				conditionAvg/=conditionValue.size();
				conditionAvg=Double.parseDouble(String.format("%.1f", conditionAvg));
			}
			else
				conditionAvg=0;
			
			if(!weightValue.isEmpty())
			{
				for(int i=0;i<weightValue.size();i++)
				{
					weightAvg+=weightValue.get(i);
					
					if(weightValue.get(i)>weightHigh)
						weightHigh=weightValue.get(i);
					if(weightValue.get(i)<weightLow)
						weightLow=weightValue.get(i);
				}
				weightAvg/=weightValue.size();
				weightAvg=Double.parseDouble(String.format("%.1f",weightAvg));
			}
			else
				weightLow=0;
			
			if(!temperValue.isEmpty())
			{
				for(int i=0;i<temperValue.size();i++)
				{
					temperAvg+=temperValue.get(i);
					
					if(temperValue.get(i)>temperHigh)
						temperHigh=temperValue.get(i);
					if(temperValue.get(i)<temperLow)
						temperLow=temperValue.get(i);
				}
				
				temperAvg/=temperValue.size();
				temperAvg=Double.parseDouble(String.format("%.1f",temperAvg));
			}
			else
				temperLow=0;
			
			if(!heartRateValue.isEmpty())
			{
				for(int i=0;i<heartRateValue.size();i++)
				{
					heartAvg+=heartRateValue.get(i);
					
					if(heartRateValue.get(i)>heartHigh)
						heartHigh=heartRateValue.get(i);
					if(heartRateValue.get(i)<heartLow)
						heartLow=heartRateValue.get(i);
				}
				
				heartAvg/=heartRateValue.size();
				heartAvg=Double.parseDouble(String.format("%.1f",heartAvg));
			}
			else
				heartLow=0;
			
			if(!pressureValue.isEmpty())
			{
				for(int i=0;i<pressureValue.size();i++)
				{
					pressureAvg+=pressureValue.get(i);
					
					if(pressureValue.get(i)>pressureHigh)
						pressureHigh=pressureValue.get(i);
					if(pressureValue.get(i)<pressureLow)
						pressureLow=pressureValue.get(i);
				}
				
				pressureAvg/=pressureValue.size();
				pressureAvg=Double.parseDouble(String.format("%.1f",pressureAvg));
			}
			else
				pressureLow=0;
			
			int statusTmp;
			for(int i=0;i<12;i++)
			{
				for(int j=i;j>0;j--)
				{
					if(statusValue[j][0]>statusValue[j-1][0])
					{
						statusTmp=statusValue[j][0];
						statusValue[j][0]=statusValue[j-1][0];
						statusValue[j-1][0]=statusTmp;
						
						statusTmp=statusValue[j][1];
						statusValue[j][1]=statusValue[j-1][1];
						statusValue[j-1][1]=statusTmp;
					}
					else
						break;
				}
			}
			
			for(int i=0;i<5;i++)
			{
				switch(statusValue[i][1])
				{
				case 1 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 입맛이 없어요";
					break;
				case 2 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 식욕이 넘쳐요";
					break;
				case 3 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 아침이 개운하지 않아요";
					break;
				case 4 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 몸이 가벼워요";
				break;
				case 5 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 감정이 오락가락 예민해요";
				break;
				case 6 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 긍정의 기운이 솟아요";
				break;
				case 7 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 하루 종일 피곤해요";
				break;
				case 8 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 기운이 넘쳐요";
				break;
				case 9 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 우울한 하루예요";
				break;
				case 10 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 오늘 기분 최고!";
				break;
				case 11 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 판단력이 떨어져요";
				break;
				case 12 : 
					if(statusValue[i][0]==0)
						statusStr[i]=String.valueOf(i+1)+".";
					else
						statusStr[i]=String.valueOf(i+1)+". 뭐든지 할 수 있을 것 같아요";
				break;
				}
			}
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
	
	public void setData()
	{
		TextView conditionText=(TextView)findViewById(R.id.condAverage);
		conditionText.setText(String.valueOf(conditionAvg));
		/*컨디션 전달/전주 대비 차이 설정 추가*/
		
		TextView statusText=(TextView)findViewById(R.id.status1);
		statusText.setText(statusStr[0]);
		statusText=(TextView)findViewById(R.id.status2);
		statusText.setText(statusStr[1]);
		statusText=(TextView)findViewById(R.id.status3);
		statusText.setText(statusStr[2]);
		statusText=(TextView)findViewById(R.id.status4);
		statusText.setText(statusStr[3]);
		statusText=(TextView)findViewById(R.id.status5);
		statusText.setText(statusStr[4]);
		
		TextView weightText=(TextView)findViewById(R.id.weightAverage);
		weightText.setText(String.valueOf(weightAvg));
		weightText=(TextView)findViewById(R.id.weightHigh);
		weightText.setText(String.valueOf(weightHigh));
		weightText=(TextView)findViewById(R.id.weightLow);
		weightText.setText(String.valueOf(weightLow));
		
		TextView temperText=(TextView)findViewById(R.id.temperAverage);
		temperText.setText(String.valueOf(temperAvg));
		temperText=(TextView)findViewById(R.id.temperHigh);
		temperText.setText(String.valueOf(temperHigh));
		temperText=(TextView)findViewById(R.id.temperLow);
		temperText.setText(String.valueOf(temperLow));
		
		TextView heartText=(TextView)findViewById(R.id.heartAverage);
		heartText.setText(String.valueOf(heartAvg));
		heartText=(TextView)findViewById(R.id.heartHigh);
		heartText.setText(String.valueOf(heartHigh));
		heartText=(TextView)findViewById(R.id.heartLow);
		heartText.setText(String.valueOf(heartLow));
		
		TextView pressureText=(TextView)findViewById(R.id.pressureAverage);
		pressureText.setText(String.valueOf(pressureAvg));
		pressureText=(TextView)findViewById(R.id.pressureHigh);
		pressureText.setText(String.valueOf(pressureHigh));
		pressureText=(TextView)findViewById(R.id.pressureLow);
		pressureText.setText(String.valueOf(pressureLow));
	}
	
	public void setReport()
	{
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		ImageButton top=(ImageButton)findViewById(R.id.top);
		AbsoluteLayout.LayoutParams params = null;
		params = (AbsoluteLayout.LayoutParams) top.getLayoutParams();
		params.x = metrics.widthPixels - 200;
		params.y = metrics.heightPixels - 200;
		top.setLayoutParams(params);
		
		try {
			PackageInfo i = getPackageManager().getPackageInfo(
					getPackageName(), 0);
		} catch (NameNotFoundException e) {
			System.out.println(e);
		}
		
		getData();
		
		setData();
		TextView side;
		ImageView sideImg;
		for(int i=1;i<20;i++)
		{
			switch(i)
			{
			case 1:
				side=(TextView)findViewById(R.id.side1);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side1img);
				break;
			case 2:
				side=(TextView)findViewById(R.id.side2);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side2img);
				break;
			case 3:
				side=(TextView)findViewById(R.id.side3);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side3img);
				break;
			case 4:
				side=(TextView)findViewById(R.id.side4);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side4img);
				break;
			case 5:
				side=(TextView)findViewById(R.id.side5);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side5img);
				break;
			case 6:
				side=(TextView)findViewById(R.id.side6);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side6img);
				break;
			case 7:
				side=(TextView)findViewById(R.id.side7);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side7img);
				break;
			case 8:
				side=(TextView)findViewById(R.id.side8);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side8img);
				break;
			case 9:
				side=(TextView)findViewById(R.id.side9);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side9img);
				break;
			case 10:
				side=(TextView)findViewById(R.id.side10);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side10img);
				break;
			case 11:
				side=(TextView)findViewById(R.id.side11);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side11img);
				break;
			case 12:
				side=(TextView)findViewById(R.id.side12);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side12img);
				break;
			case 13:
				side=(TextView)findViewById(R.id.side13);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side13img);
				break;
			case 14:
				side=(TextView)findViewById(R.id.side14);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side14img);
				break;
			case 15:
				side=(TextView)findViewById(R.id.side15);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side15img);
				break;
			case 16:
				side=(TextView)findViewById(R.id.side16);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side16img);
				break;
			case 17:
				side=(TextView)findViewById(R.id.side17);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side17img);
				break;
			case 18:
				side=(TextView)findViewById(R.id.side18);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side18img);
				break;
			case 19:
				side=(TextView)findViewById(R.id.side19);
				side.setText(String.valueOf(sideEffectValue[i][0]));
				sideImg=(ImageView)findViewById(R.id.side19img);
				break;
			}
			
			//값에따라 그래프 그리기
			if(sideEffectValue[i][0]>=0 && sideEffectValue[i][0]<=6)
			{
				
			}
			else if(sideEffectValue[i][0]>=7 && sideEffectValue[i][0]<=12)
			{
				
			}
			else if(sideEffectValue[i][0]>=13 && sideEffectValue[i][0]<=18)
			{
				
			}
			else if(sideEffectValue[i][0]>=19 && sideEffectValue[i][0]<=24)
			{
				
			}
			else if(sideEffectValue[i][0]>=25)
			{
				
			}
		}
		
//		sideEffect = (Chart) findViewById(R.id.sideEffects);
//		sideEffect.setChartType(Chart.Chart_Type_Clustered_Bar);
//		
//		sideEffect.setTitleVisible(false);
//		sideEffect.setTitleFontSize(20);
//		sideEffect.setTitleFontStyle(1);
//
//		gridData = new GridData(nRows, nColumns);
//
//		String[] strRow = { "0", "구역, 구토", "설사, 복통", "두통", "어지러움", "변비", "가슴통증", "출혈, 멍", "대소변이 검거나 붉은색", "근육통, 관절통", "부종, 얼굴이 붓는다.", "경련, 발작", "불면증", "탈수증", "호흡곤란", "고열", "발한", "손발저림, 따끔거림, 감각이상", "두드러기, 피부과민반응", "눈물, 눈부심" };
//		String[] strCol = { "0", "1" };
//
//		for (int nRow = 0; nRow < nRows; nRow++) {
//			for (int nColumn = 0; nColumn < nColumns; nColumn++) {
//				if (nRow == 0)
//					gridData.setCell(nRow, nColumn, strCol[nColumn]);
//				else if (nColumn == 0)
//					gridData.setCell(nRow, nColumn, strRow[nRow]);
//				else
//					gridData.setCell(nRow, nColumn, sideEffectValue[nRow - 1][nColumn - 1]);
//			}
//		}
//		int plotBy = 0;
//		sideEffect.setSourceData(gridData, plotBy);
//		sideEffect.setLegendVisible(false);
	}
	
	public void setImage(int i, double[][] value)
	{
		switch(i)
		{
			
		}
	}
	
	void initData()
	{
		conditionValue.clear();
		for(int i=0;i<19;i++)
			sideEffectValue[i][0]=0;
		weightValue.clear();
		weightAvg=0;
		weightHigh=0;
		weightLow=9999;
		temperValue.clear();
		temperAvg=0;
		temperHigh=0;
		temperLow=9999;
		heartRateValue.clear();
		heartAvg=0;
		heartHigh=0;
		heartLow=9999;
		pressureValue.clear();
		pressureAvg=0;
		pressureHigh=0;
		pressureLow=9999;
		for(int i=0;i<12;i++)
			statusValue[i][0]=0;
		for(int i=0;i<5;i++)
			statusStr[i]="";
	}
}
